package com.google.code.jbauble.mvc.support;

import javax.servlet.http.HttpServletRequest;

public class UrlHelper {
	public static final int HTTP_ALL = 0;
	public static final int HTTP_GET = 1;
	public static final int HTTP_POST = 2;
	public static final int HTTP_PUT = 3;
	public static final int HTTP_DELETE = 4;
	
	private static String sprit = "/";
	
	/**
	 * 合并两段url
	 * 如：user和list，合并为/user/list/
	 * @param cu controller的url
	 * @param mu action的url
	 * @return 返回合并后的url
	 */
	public static String mergeUrl(String cu, String mu) {
		String url = "";
		if (!cu.startsWith(sprit)) {
			url += sprit;
		}
		url += cu;
		if (!cu.endsWith(sprit)) {
			url += sprit;
		}
		if (mu == null || mu.equals("") || mu.equals(sprit))
			return url;
		
		if (mu.startsWith(sprit)) {
			url += mu.substring(1);
		}
		else {
			url += mu;
		}
		if (!mu.endsWith(sprit)) {
			url += sprit;
		}
		return url;
	}
	
	public static String getRequestUrl(HttpServletRequest request) {
		String url = request.getRequestURI();
		String base = request.getContextPath();
		url = url.substring(base.length());
		if (!url.endsWith(sprit)) {
			url += sprit;
		}
		return url;
	}

	public static int getHttpMehtod(String method) {
		String m = method.toLowerCase();
		if (m.equals("get"))
			return HTTP_GET;
		if (m.equals("post"))
			return HTTP_POST;
		if (m.equals("put"))
			return HTTP_PUT;
		if (m.equals("delete"))
			return HTTP_DELETE;
		
		//TODO: dispose error
		return -1;
	}
	
	public static String getControllerSimpleName(String simpleName) {
		String name = simpleName;
		int index = name.indexOf("Controller");
		if (index > -1) {
			name = name.substring(0, index);
		}
	
		return name.substring(0, 1).toLowerCase() + name.substring(1);
	}
}
